const router = require('koa-router')()
const dbhealper = require('../utils/dbhealper');
const jwt = require('jsonwebtoken');

router.prefix('/user')

router.get('/info', async (ctx, next) => {
  const uid = ctx.state.user.id;
  const userInDb = await dbhealper.makePromise(
    ctx.state.sqlconn,
    'select id, nickname, username from admin where id=?',
    [uid]
  );
  ctx.body = {
    code: 200,
    msg: 'ok',
    data: userInDb.length > 0 ? userInDb[0] : null
  };
})

router.post('/login', async function (ctx, next) {
  const qbody = ctx.request.body;
  const username = qbody.username;
  const password = qbody.password;
  const query = 'select * from admin where username=? and password=?;';
  const users = await dbhealper.makePromise(ctx.state.sqlconn, query, [username, password]);
  if (users.length > 0) {
    const us = users[0];
    const payload = {
      exp: Date.now() + 1000 * 60 * 60 * 24 * 7,
      id: us.id,
      username: us.username
    };
    const tokenKey = 'luckhall';
    const token = jwt.sign(payload, tokenKey);
    ctx.set('authorization', 'Bearer ' + token);
    ctx.set('Access-Control-Expose-Headers', 'authorization');
    ctx.body = {
      code: 200,
      msg: 'ok',
      data: {
        username: us.username,
        nickname: us.nickname,
        token: 'Bearer ' + token
      }
    };
  } else {
    ctx.body = {code: 605, msg: '登录失败，错误的用户名或密码', body: null};
  }
})


module.exports = router
